package org.nlp2rdf.navigator.client;

import java.util.LinkedHashMap;
import java.util.Map;

import org.nlp2rdf.navigator.client.common.ExampleDTO;
import org.nlp2rdf.navigator.client.common.SearchResultDTO;
import org.nlp2rdf.navigator.client.functionality.ExampleWidget;
import org.nlp2rdf.navigator.client.functionality.TitleWidget;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class SearchResultWidget extends Composite {

	private VerticalPanel matchingExamplesTable = new VerticalPanel();;
	private Map<String, ExampleDTO> matchingExampleDTOs = new LinkedHashMap<String, ExampleDTO>();

	private VerticalPanel nonmatchingExamplesTable = new VerticalPanel();
	private Map<String, ExampleDTO> nonMatchingExampleDTOs = new LinkedHashMap<String, ExampleDTO>();

	private VerticalPanel posNeg = new VerticalPanel();

	final private TitleWidget titleWidget = new TitleWidget("Search Results", posNeg);

	final private Application app;

	public SearchResultWidget(Application app) {
		this.app = app;
		VerticalPanel outerBoundPanel = new VerticalPanel();
		outerBoundPanel.add(titleWidget);

		collapse(true);

		// positive List
		Label matches = new Label("Positive Matches");
		matches.addStyleName("module-subtitle");
		posNeg.add(matches);
		posNeg.add(matchingExamplesTable);

		// negative List
		Label nonMatches = new Label("random Negatives");
		nonMatches.addStyleName("module-subtitle");
		posNeg.add(nonMatches);
		posNeg.add(nonmatchingExamplesTable);

		// total
		outerBoundPanel.add(posNeg);
		outerBoundPanel.setWidth("95%");
		outerBoundPanel.addStyleName("module-border");
		outerBoundPanel.addStyleName("greyed");

		draw();

		initWidget(outerBoundPanel);

	}

	public void collapse(boolean collapse) {
		titleWidget.collapse(collapse);
	}

	/**
	 * This will empty the widget and show the new examples
	 * 
	 * @param searchResultDTO
	 */
	public void updateSearchResults(SearchResultDTO searchResultDTO) {
		matchingExampleDTOs.clear();
		for (ExampleDTO matching : searchResultDTO.getMatching()) {
			if (!app.positiveNegativeWidget.contains(matching)) {
				matchingExampleDTOs.put(matching.getUri(), matching);
			}
		}
		nonMatchingExampleDTOs.clear();
		for (ExampleDTO nonMatching : searchResultDTO.getNotMatching()) {
			if (!app.positiveNegativeWidget.contains(nonMatching)) {
				nonMatchingExampleDTOs.put(nonMatching.getUri(), nonMatching);
			}
		}
		draw();

	}

	private void draw() {
		// flush tables
		matchingExamplesTable.clear();
		nonmatchingExamplesTable.clear();

		// add content
		ExampleWidget.addExamplesToSelectionTable(app, matchingExampleDTOs, matchingExamplesTable);
		ExampleWidget.addExamplesToSelectionTable(app, nonMatchingExampleDTOs, nonmatchingExamplesTable);

	}
}
